//
//  VideoViewController.m
//  ExploreWorld
//
//  Created by dlios on 15/7/13.
//  Copyright (c) 2015年 chenlin. All rights reserved.
//

#import "VideoViewController.h"
#import  "Header.h"
#import "ListenModel.h"
#import "ListenNormalTableViewCell.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "WeatherViewController.h"
#import "LivingViewController.h"

#import "DataBaseManager.h"
#import "CollectModel.h"






@interface VideoViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    UIView *contentView;
    UPStackMenu *stack;
    
}
@end

@implementation VideoViewController

-(void)loadView
{
    [super loadView];
    [self createTitleView];
    [self creteLivingButton];
    [self createlistenTableView];
    [self tableNetRequest];
    

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    [self.view setBackgroundColor:[UIColor grayColor]];
    // 自定义导航栏返回按钮
    
    contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"caidanzhankai.png"]];
    [icon setContentMode:UIViewContentModeScaleAspectFit];
    [icon setFrame:CGRectInset(contentView.frame, 10, 10)];  //只能写10 10，大了不显示
    [contentView addSubview:icon];
    [self touchClick:nil];
    
}
- (void)touchClick:(id)sender
{
    if(stack)
        [stack removeFromSuperview];
    stack = [[UPStackMenu alloc] initWithContentView:contentView];
    [stack setCenter:CGPointMake(15, 15)];
    [stack setDelegate:self];
    [stack setBackgroundColor:[UIColor whiteColor]];
    UPStackMenuItem *squareItem = [[UPStackMenuItem alloc] initWithImage:nil highlightedImage:nil title:@"CCTV-13"];
    UPStackMenuItem *circleItem = [[UPStackMenuItem alloc] initWithImage:nil highlightedImage:nil title:@"CCTV-1"];
    UPStackMenuItem *triangleItem = [[UPStackMenuItem alloc] initWithImage:nil highlightedImage:nil title:@"CCTV-9"];
    NSMutableArray *items = [[NSMutableArray alloc] initWithObjects:squareItem, circleItem, triangleItem,  nil];
    [stack setAnimationType:UPStackMenuAnimationType_linear];
    [stack setStackPosition:UPStackMenuStackPosition_down];
    [stack setOpenAnimationDuration:.3];
    [stack setCloseAnimationDuration:.3];
    [items enumerateObjectsUsingBlock:^(UPStackMenuItem *item, NSUInteger idx, BOOL *stop) {
        [item setLabelPosition:UPStackMenuItemLabelPosition_right];
    }];
    [stack addItems:items];
    [self.view addSubview:stack];
    [stack setBackgroundColor:[UIColor clearColor]];
    [self setStackIconClosed:YES];
}

- (void)setStackIconClosed:(BOOL)closed
{
    UIImageView *icon = [[contentView subviews] objectAtIndex:0];
    float angle = closed ? 0 : (M_PI * (135) / 180.0);
    [UIView animateWithDuration:0.3 animations:^{
        [icon.layer setAffineTransform:CGAffineTransformRotate(CGAffineTransformIdentity, angle)];
    }];
}

#pragma mark - UPStackMenuDelegate

- (void)stackMenuWillOpen:(UPStackMenu *)menu
{
    if([[contentView subviews] count] == 0)
        return;
    
    [self setStackIconClosed:NO];
}

- (void)stackMenuWillClose:(UPStackMenu *)menu
{
    if([[contentView subviews] count] == 0)
        return;
    
    [self setStackIconClosed:YES];
}

- (void)stackMenu:(UPStackMenu *)menu didTouchItem:(UPStackMenuItem *)item atIndex:(NSUInteger)index
{
    NSString *strForPlay = [self returnPlayUrl:index];
    LivingViewController *liv = [[LivingViewController alloc]init];
    liv.url = strForPlay;
    [self.navigationController pushViewController:liv animated:YES];
    
    
}

//给一个index，返回播放网址
- (NSString *)returnPlayUrl:(NSInteger)index
{
    NSString *s = nil;
    if (index == 0) {
        //cctv13
        s = @"http://121.199.63.236:7613/m3u8/btv/cctv13.m3u8?from=bab&fun=yes&chk=y&chunk=xax&pwd=yuntutv&nwtime=1437016386&sign=8935c0df19500dfdb877fda043b0a99f";
    }
    //cctv1
    if (index == 1) {
        s = @"http://115.29.223.211:7613/m3u8/btv/cctv1.m3u8?from=bab&fun=yes&chk=y&chunk=xax&pwd=yuntutv&nwtime=1437037009&sign=959423983ccc67037b819d73ef2c078e";
    }
    
    //cctv9
    if (index == 2) {
        s = @"http://121.199.55.88:7613/m3u8/btv/cctv9.m3u8?from=bab&fun=yes&chk=y&chunk=xax&pwd=yuntutv&nwtime=1437037303&sign=21a04440eef692d4d8feeb9c1aae7120";
    }
    return s;
}









- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)dealloc
{
    //[self.titleScroll release];
    [self.datePicker release];
    [self.table release];
    [self.date release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.videoList = [NSMutableArray array];
    }
    return  self;
}



#pragma mark -
#pragma mark 顶端直播界面
-  (void)createTitleView
{
    UIImageView *ima = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH / 2)];
    [ima  setImage:[UIImage imageNamed:@"cctv_tower.png"]];
    [self.view addSubview:ima];
}


#pragma mark -
#pragma mark 创建往期节目
- (void)creteLivingButton
{
    //创建时间选择器的按钮
    UIButton *dateChoose = [[UIButton alloc]initWithFrame:CGRectMake(20, WIDTH / 2 + 10, 60, 30)];
    [dateChoose setTitle:@"往期" forState:UIControlStateNormal];
    [dateChoose setBackgroundColor:[UIColor purpleColor]];
    [dateChoose addTarget:self action:@selector(createDatePicker:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:dateChoose];
    [dateChoose release];
    
    //进入天气
    UIButton *Now = [[UIButton alloc]initWithFrame:CGRectMake(100, WIDTH / 2 + 10, 60, 30)];
    [Now setTitle:@"天气" forState:UIControlStateNormal];
    [Now setBackgroundColor:[UIColor purpleColor]];
    [Now addTarget:self action:@selector(NowClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:Now];
    [Now release];
}

- (void)NowClick:(id)sender
{
    WeatherViewController *WE = [[WeatherViewController alloc]init];
    [self presentViewController:WE animated:YES completion:nil];
}

//点击往期按钮，创建UiDatePicker
- (void)createDatePicker:(id)sender
{
    //获取当前区域
    NSLocale *China = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
    
    
    
    self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 200, self.view.frame.size.width, 200)];
    //将时间选择器的区域设置为中国
    [self.datePicker setLocale:China];
    
    [self.datePicker setBackgroundColor:[UIColor grayColor]];
    [self.datePicker setDatePickerMode: UIDatePickerModeDate];
    [self.datePicker addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.datePicker];
    //[self.datePicker release];
}


//当前值一旦变化，调用此方法
- (void)dateChange:(id)sender
{
    UIDatePicker *control = (UIDatePicker *)sender;
    self.date = control.date;
    [self.datePicker release];
    [self searchNewsByDate];
    [self.datePicker removeFromSuperview];
    
}

#pragma mark - 输入日期，搜索新闻内容（先对self.date进行字符串截取，然后拼接网址，网络请求，加载数据）
- (void)searchNewsByDate
{
    DataBaseManager *dbManager = [DataBaseManager shareInstance];
    [dbManager openDB];
    NSMutableArray *arr =  [dbManager   selectInfoFromNewsCollect];
    
    self.videoList = [NSMutableArray array];
    
    NSString *date = [NSString stringWithFormat:@"%@",self.date];
    //  NSLog(@"%@",date);
    
    NSArray *array = [date componentsSeparatedByString:@" "];
    NSString *str = array[0];
    NSString *year = [str substringWithRange:NSMakeRange(0, 4)];
    NSString *month = [str substringWithRange:NSMakeRange(5, 2)];
    NSString *day = [str substringWithRange:NSMakeRange(8, 2)];
    NSString *pickDate = [NSString stringWithFormat:@"%@%@%@",year,month,day];
    NSLog(@"%@",pickDate);
    // http://hot.news.cntv.cn/index.php?controller=lanmu&action=getvideolist&id=PAGE1354766409225382&n=50&time=
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    NSString *str1 = [NSString stringWithFormat:@"http://hot.news.cntv.cn/index.php?controller=lanmu&action=getvideolist&id=PAGE1354766409225382&n=50&time=%@",pickDate];
    
    [manager1 GET:str1 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData *data = operation.responseData;
        NSDictionary *BigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *videoListArray = [BigDic objectForKey:@"videoList"];
        for (NSMutableDictionary *smallDic  in videoListArray) {
            ListenModel *model = [[ListenModel alloc]init];
            model.title = [smallDic objectForKey:@"videoTitle"];
            model.image = [smallDic objectForKey:@"videoImage"];
            model.videoID = [smallDic objectForKey:@"videoPlayID"];
            
            [self.videoList addObject:model];
            for (CollectModel *find in arr) {
                if ([model.title isEqualToString:find.title]) {
                    model.collectioned = YES;
                }
            }
        }
        [self.table reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
}





#pragma mark -
#pragma mark 创建收听界面的tableView
-(void)createlistenTableView
{
    float x = WIDTH / 2 + 50;
    self.table = [[UITableView alloc]initWithFrame:CGRectMake( 0, WIDTH / 2 + 50, WIDTH, HEIGHT - 50 - WIDTH / 2) style:UITableViewStylePlain];
    [self.table setRowHeight:x];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
}

//tableView两个必须实现的代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videoList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellnormal = @"cellnormal";
    
    
    
    ListenModel *model = [self.videoList objectAtIndex:indexPath.row];
    
    ListenNormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellnormal];
    if (!cell) {
        cell = [[ListenNormalTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellnormal];
    }
    
    cell.collectButton.listen = model;
    cell.titleLable.text = model.title;
    [cell.cellImage  sd_setImageWithURL:[NSURL URLWithString:model.image]placeholderImage:[UIImage imageNamed:@"placeHold.png"] options:SDWebImageRetryFailed];
    
    cell.model = model;
    
    CollectModel *collect = [[CollectModel alloc]init];
    collect.title = model.title;
    [cell.collectButton setImage:[UIImage imageNamed:@"shoucang.png"] forState:UIControlStateNormal];
    
    if (model.collectioned) {
        [cell.collectButton setImage:[UIImage imageNamed:@"finishshoucang.png"] forState:UIControlStateNormal];
    }
    
    return cell;
}

//tableView的网络请求
-(void)tableNetRequest
{
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    
    
    DataBaseManager *dbManager = [DataBaseManager shareInstance];
    [dbManager openDB];
    NSMutableArray *arr =  [dbManager   selectInfoFromNewsCollect];
    
    // NSString *str1 = [NSString stringWithFormat:@"http://gslb.hfy.bestvcdn.com/live/program/_hfyd-1_/live/cctv1hd/live.m3u8?se=anhui&ct=2"];
    // 正确的网址
    NSString *str1 = [NSString stringWithFormat:@"http://hot.news.cntv.cn/index.php?controller=lanmu&action=getlastvideolist&id=PAGE1354766409225382&n=50"] ;
    
    [manager1 GET:str1 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData *data = operation.responseData;
        NSDictionary *BigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *videoListArray = [BigDic objectForKey:@"videoList"];
        for (NSMutableDictionary *smallDic  in videoListArray) {
            ListenModel *model = [[ListenModel alloc]init];
            model.title = [smallDic objectForKey:@"videoTitle"];
            model.image = [smallDic objectForKey:@"videoImage"];
            model.videoID = [smallDic objectForKey:@"videoPlayID"];
            [self.videoList addObject:model];
            for (CollectModel *find in arr) {
                if ([model.title isEqualToString:find.title]) {
                    model.collectioned = YES;
                }
            }
            
        }
        [self.table reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}


#pragma mark -
#pragma maek 点击cell在当前cell的位置创建播放界面

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.streamPlayer) {
        [self.streamPlayer.view removeFromSuperview];
    }
    
    UITableViewCell *cell =   [tableView cellForRowAtIndexPath:indexPath];
    
    int  x = cell.frame.origin.x;
    int y = cell.frame.origin.y;
    
    ListenModel *model = [self.videoList objectAtIndex:indexPath.row];
    NSString *str = [NSString stringWithFormat:@"http://asp.cntv.lxdns.com/asp/hls/200/0303000a/3/default/%@/200.m3u8",model.videoID];
    
    
    NSURL *streamURL = [NSURL URLWithString:str];
    self.streamPlayer = [[MPMoviePlayerController alloc] initWithContentURL:streamURL];
    [self.streamPlayer.view setFrame:self.view.bounds];
    self.streamPlayer.controlStyle =MPMovieControlStyleEmbedded;
    
    [self.streamPlayer.view setFrame:CGRectMake(x, y,cell.frame.size.width,cell.frame.size.width/2)];
    [self.table addSubview: self.streamPlayer.view];
    [self.streamPlayer play];
    
    CollectModel *collModel =  [[CollectModel alloc]init];
    collModel.ima = model.image;
    collModel.title  =model.title;
    collModel.mediaUrl = model.mediaUrl;
    DataBaseManager *dbManager = [DataBaseManager shareInstance];
    [dbManager openDB];
    [dbManager insertInfoWithNewsHistory:collModel];
}







@end
